package com.tuyrt.hi.ui.banner.indicator

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import com.tuyrt.hi.library.util.HiDisplayUtil
import com.tuyrt.hi.ui.R

/**
 * author: Administrator on 2021/5/24.
 * desc: 圆形治指示器
 */
class HiCircleIndicator @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr),HiIndicator<FrameLayout> {

    companion object {
        private const val VWC = ViewGroup.LayoutParams.WRAP_CONTENT
    }
    /**
     * 正常状态下的指示点
     */
    @DrawableRes
    private val mPointNormal = R.drawable.shape_point_normal
    /**
     * 选中状态下的指示点
     */
    @DrawableRes
    private val mPointSelected = R.drawable.shape_point_select
    /**
     *  指示点左右的间距
     */
    private var mPointLeftRightPadding =0
    /**
     *  指示点上下的间距
     */
    private var mPointTopBottomPadding =0

    init {
        mPointLeftRightPadding = HiDisplayUtil.dp2px(5f, getResources())
        mPointTopBottomPadding = HiDisplayUtil.dp2px(15f, getResources())
    }

    override fun get(): FrameLayout {
       return this
    }

    override fun onInflate(count: Int) {
        removeAllViews()
        if (count <= 0) {
            return
        }

        val groupView = LinearLayout(context)
        groupView.orientation = LinearLayout.HORIZONTAL
        val imageViewParams =
            LinearLayout.LayoutParams(HiCircleIndicator.VWC, HiCircleIndicator.VWC)
        imageViewParams.gravity = Gravity.CLIP_HORIZONTAL
        imageViewParams.setMargins(
            mPointLeftRightPadding,
            mPointTopBottomPadding,
            mPointLeftRightPadding,
            mPointTopBottomPadding
        )
        var pointView: ImageView
        for (i in 0 until count) {
            pointView = ImageView(context)
            pointView.layoutParams = imageViewParams
            if (i == 0) {
                pointView.setImageResource(mPointSelected)
            } else {
                pointView.setImageResource(mPointNormal)
            }
            groupView.addView(pointView)
        }
        val groupViewParams = LayoutParams(VWC, VWC)
        groupViewParams.gravity = Gravity.CENTER or Gravity.BOTTOM
        addView(groupView, groupViewParams)
    }

    override fun onPointChange(current: Int, count: Int) {
        val groupView = getChildAt(0) as ViewGroup
        for (i in 0 until groupView.childCount) {
            val pointView = groupView.getChildAt(i) as ImageView
            if (i == current) {
                pointView.setImageResource(mPointSelected)
            } else {
                pointView.setImageResource(mPointNormal)
            }
            pointView.requestLayout()
        }
    }
}